﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CodeCamp.Controllers
{
  /// <summary>
  /// Extension methods on List&lt;T&gt; and IList&lt;T&gt;
  /// </summary>
  public static class ListExtensions
  {
    /// <summary>
    /// Randomly permute the items in a IList&lt;T&gt;
    /// </summary>
    /// <typeparam name="T">The parameterized type of the IList&lt;T&gt;</typeparam>
    /// <param name="list">The list to be permuted</param>
    public static void PermuteRandomly<T>( this IList<T> list )
    {
      // seed the random number generator
      DateTime now = DateTime.Now;
      Random random = new Random( (now.Minute * 60 + now.Second) * 1000 + now.Millisecond ); 

      // move randomly selected unmoved items to the end of the list
      int unmovedItems = list.Count;
      while ( unmovedItems > 0 )
        list.MoveToEnd( random.Next( unmovedItems-- ) );
    }

    /// <summary>
    /// Move an item in an IList&lt;T&gt; to the end of the list
    /// </summary>
    /// <typeparam name="T">The parameterized type of the IList&lt;T&gt;</typeparam>
    /// <param name="list">The list to be acted upon.</param>
    /// <param name="index">The index of the list item to be moved.</param>
    public static void MoveToEnd<T>( this IList<T> list, int index )
    {
      list.Add( list[ index ] );
      list.RemoveAt( index );
    }
  }
}